package com.example.word.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.dict.R;
import com.example.word.bean.Dict;
import com.example.word.bean.User;
import com.example.word.bean.Word;
import com.example.word.ui.fragment.HomeFragment;
import com.example.word.util.CommonUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.SPUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 欢迎页面
 */
public class OpeningActivity extends AppCompatActivity {
    private Activity myActivity;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myActivity = this;
        //设置页面布局
        setContentView(R.layout.activity_opening);
        initView();
    }

    private void initView() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
                    finish();
                    return;
                }
                Boolean isFirst = (Boolean) SPUtils.get(myActivity, SPUtils.IF_FIRST, true);
                String account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
                if (isFirst) {//第一次进来  初始化本地数据
                    SPUtils.put(myActivity, SPUtils.IF_FIRST, false);//第一次
                    //初始化数据
                    //获取json数据
                    StringBuilder rewardJson = new StringBuilder();
                    String rewardJsonLine;
                    //assets文件夹下db.json文件的路径->打开db.json文件
                    HttpUtils.sendGetRequestStringResponse(CommonUtils.dictUrl, new HashMap<>(), responseString -> {
                        // 处理请求成功的情况
                        try {
                            JSONObject jsonObject = new JSONObject(responseString);
                            //获得列表
                            JSONArray dictList = jsonObject.getJSONArray("cates");
                            //把物品列表保存到本地
                            List<Dict> dicts = new ArrayList<>(dictList.length());
                            for (int i = 0, length = dictList.length(); i < length; i++) {
                                JSONObject cate = dictList.getJSONObject(i);
                                int typeId = 3;
                                int typeIdIndex = HomeFragment.title.indexOf(cate.getString("cateName"));

                                if (typeIdIndex != -1) {
                                    typeId = typeIdIndex;
                                }
                                JSONArray bookList = cate.getJSONArray("bookList");

                                for (int bookIndex = 0; bookIndex < bookList.length(); bookIndex++) {
                                    JSONObject jsonBook = bookList.getJSONObject(bookIndex);
                                    // 暂不记录作者信息
                                    /*String issuer = "";
                                    try {
                                        JSONObject bookOrigin = jsonBook.getJSONObject("bookOrigin");
                                        issuer = bookOrigin.getString("originName");
                                    } catch (Exception e) {
                                        issuer = "球球单词";
                                    }*/

                                    String content = "该词汇属于【"
                                            + jsonBook.getString("cateName") + "】，"
                                            + jsonBook.getString("title")
                                            + " (词汇量 " + jsonBook.getString("wordNum") + ")";
                                    Dict book = new Dict(Integer.parseInt(HomeFragment.state.get(typeId)),
                                            jsonBook.getString("title"),
                                            jsonBook.getString("cover"),
                                            jsonBook.getString("offlinedata"),
                                            content,
                                            jsonBook.getInt("wordNum"),
                                            sf.format(new Date())
                                    );
                                    dicts.add(book);
                                }
                            }
                            Collections.sort(dicts, new Comparator<Dict>() {
                                @Override
                                public int compare(Dict dict1, Dict dict2) {
                                    return Integer.compare(dict1.getWordNumber(), dict2.getWordNumber());
                                }
                            });
                            Dict.saveAll(dicts);

                            // 初始化默认用户
                            User user = new User("admin", "admin", "管理员", "16329572433");
                            user.save();
                            User user1 = new User("t", "t", "测试人员", "16329572433");
                            user1.save();
                            // 跳转到主页面
                            Intent intent = new Intent();
                            intent.setClass(OpeningActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        } catch (Exception e) {
                            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                        }
                    });
                } else {
                    //两秒后跳转到主页面
                    Intent intent = new Intent();
                    intent.setClass(OpeningActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        }, 1500);
    }

    @Override
    public void onBackPressed() {

    }
}
